package br.elsa.survey.view.beans.managed;

import java.util.Set;

import javax.inject.Inject;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import br.elsa.survey.domain.questions.Question;
import br.elsa.survey.domain.questions.QuestionsFactory;
import br.elsa.survey.services.QuestionService;
import br.elsa.survey.view.messages.ViewMessages;

public abstract class AbstractQuestionCreationView {

	/**
	 * Injects an instance of {@link QuestionService}, responsible to hold all
	 * business logic process over a {@link Question}.
	 */
	@Inject
	protected QuestionService questionService;

	@Inject
	protected QuestionsFactory questionsFactory;

	/**
	 * Component used to put messages into view context.
	 */
	@Inject
	protected ViewMessages viewMessages;

	public AbstractQuestionCreationView() {

	}

	public AbstractQuestionCreationView(QuestionsFactory questionsFactory, QuestionService questionService, ViewMessages viewMessages) {

		this.questionsFactory = questionsFactory;
		this.questionService = questionService;
		this.viewMessages = viewMessages;
	}

	/**
	 * Action binded to the Save button in the view. This action delegates the
	 * Responsibility of creating a {@link Question} to the
	 * {@link QuestionService} business logic class.
	 */
	public void createQuestion() {

		try {
			questionService.create(getNewQuestion());
			viewMessages.addInfoMessage("New question created");

			resetViewState();

		} catch (ConstraintViolationException e) {

			Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
			for (ConstraintViolation<?> violation : constraintViolations) {
				viewMessages.addErrorMessage(violation.getMessage());
			}
		}
	}

	/**
	 * Resets the controller state after a question is created.
	 */
	public abstract void resetViewState();

	/**
	 * Gets the instance of the question that is being created
	 * 
	 * @return the instance of the question that is being created
	 */
	public abstract Question getNewQuestion();

}
